console.log("service worker")
getCurrentTab()
createMenus()

// 获取当前选项卡ID
async function getCurrentTab() {
  let queryOptions = { active: true, lastFocusedWindow: true }
  // `tab` will either be a `tabs.Tab` instance or `undefined`.
  let [tab] = await chrome.tabs.query(queryOptions)
  console.log(tab)
  return tab
}

// 创建存储数据菜单
function createMenus() {
  chrome.contextMenus.create(
    {
      id: "setStorage",
      type: "normal",
      title: "setStorage",
      // MV3取消该方法，改用chrome.contextMenus.onClicked事件监听
      // onclick: (info: any, tab: any) => {
      //   console.log(info, tab, 'tab')
      //   // chrome.tabs.sendMessage(tab.id as number, JSON.stringify(info), (response) => {
      //   //   console.log(response,'response')
      //   // })
      //   // }
      // },
    },
    () => {
      // 创建菜单完成后的回调
      console.log("setStorage菜单创建")
    }
  )
  // 创建获取数据菜单
  chrome.contextMenus.create(
    {
      id: "getStorage",
      type: "normal",
      title: "getStorage",
    },
    () => {
      // 创建菜单完成后的回调
      console.log("getStorage菜单创建")
    }
  )
}
// 监听菜单点击事件
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  const storageInfo = await chrome.storage.sync.get("storageData")
  if (!storageInfo.storageData) {
    // return message.error('请先通过插件弹出页面设置存储类型和key！')
    createNotification({ title: "storage键值对设置状态", message: "请先通过插件弹出页面设置存储类型和key！" })
    return
  }
  // 发送消息
  chrome.tabs.sendMessage(
    tab?.id as number,
    {
      menuItemId: info.menuItemId,
      storageData: storageInfo.storageData,
    },
    (response) => {
      console.log("background receive response :", response)
      if (response) {
        createNotification({ title: "存储操作结果", message: (info.menuItemId === "setStorage" ? "设置" : "获取") + "storage成功" })
      } else {
        createNotification({ title: "存储操作结果", message: (info.menuItemId === "setStorage" ? "设置" : "获取") + "storage失败" })
      }
    }
  )
})
// 监听消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log(sender, "background receive sender")
  createNotification({ title: "contentscript加载状态", message: request })
})
// 封装通知方法
function createNotification(data: Record<string, string>) {
  let notificationId: string | null = null
  chrome.notifications.clear("storageNotication")
  chrome.notifications.create(
    "storageNotication",
    {
      type: "basic",
      title: data.title,
      message: data.message,
      iconUrl: "./src/assets/icons/icon48.png",
    },
    (id) => {
      console.log("notifications created success:", id)
      notificationId = id
    }
  )
  return notificationId
}
export {}
